package com.awenhui.demo.interceptor;

import com.awenhui.demo.core.base.ActionResult;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author yuxf
 * @version 1.0
 * @date 2020/5/19 15:48
 */
@Component
public class MyInterceptor implements HandlerInterceptor {

    @Value("${app.open}")
    private boolean open;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
       // System.out.println("拦截：" + request.getRequestURI()+",open:"+open);

        if (!open) return true;
        String token = request.getHeader("Authorization");
        if (StringUtils.isBlank(token))
            token = request.getParameter("Authorization");
        if (StringUtils.isBlank(token)) {
            writerResponse(0,"未授权",null,response);
            return false;
        }
        return true;
    }

    /**
     * 响应输出
     *
     * @param code     ${@link Integer} 响应代码
     * @param message  ${@link String} 响应消息
     * @param model    ${@link T} 响应数据
     * @param response ${@link HttpServletResponse}
     * @author zhouxuanhong
     * @date 2019-05-15 15:21
     */
    public static <T> void writerResponse(Integer code, String message, T model, HttpServletResponse response) throws IOException {
        ActionResult<T> actionResult = new ActionResult<>();
        if (code == 0) {
            actionResult.setSuccess(true);
        } else {
            actionResult.setSuccess(false);
        }
        actionResult.setMessage(message);
        actionResult.setCode(code);
        actionResult.setData(model);
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        response.setHeader("Access-Control-Allow-Origin", CorsConfiguration.ALL);
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
        response.setHeader("Access-Control-Max-Age", "3600");
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.writeValue(response.getOutputStream(), actionResult);
    }

}
